from alipay import AliPay, AliPayConfig
from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.orders.models import OrderInfo
from apps.pay.models import Payment
from meiduomall import settings
from utils.response_code import RETCODE
from utils.views import LoginRequiredJSONMixin


class PaymentView(LoginRequiredJSONMixin, View):
    def get(self, request, order_id):
        # 1、接受验证订单
        try:
            # 为了让查询更准确，所以应该查询还没有支付的
            order = OrderInfo.objects.get(order_id=order_id,
                                          user=request.user,
                                          status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '暂无此订单'})
        # 2、创建alipay实例对象
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA",  # RSA 或者 RSA2
            debug=True,  # 默认False
            verbose=False,  # 输出调试数据
            config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
        )
        # 3、生成order_string
        # 如果你是 Python 3的用户，使用默认的字符串即可
        subject = "测试订单"
        # subject = order_id

        # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        # 正式环境：https://openapi.alipay.com/gateway.do? + order_string
        # 沙箱环境：https://openapi.alipaydev.com/gateway.do
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject=subject,
            return_url=settings.ALIPAY_RETURN_URL,
            # return_url=None,
        )
        # 4、拼接调转url
        pay_url = settings.ALIPAY_URL + '?' + order_string
        # ５、返回
        return http.JsonResponse({'code': RETCODE.OK, 'pay_url': pay_url})


class PayStatusView(View):
    def get(self, request):
        """
        讲订单ID和支付宝ID保存起来
        """
        # 1、创建支付宝实例
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA",  # RSA 或者 RSA2
            debug=True,  # 默认False
            verbose=False,  # 输出调试数据
            config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
        )
        # 2、获取验证数据
        data = request.GET.dict()
        # sign不参与签名验证
        signature = data.pop('sign')
        # verify
        success = alipay.verify(data, signature)
        if success:
            # 保存数据
            trade_no = data.get('trade_no')  # 支付宝交易号
            out_trade_no = data.get('out_trade_no')  # 商户订单号

            Payment.objects.create(
                order_id=out_trade_no,
                trade_id=trade_no
            )

        return render(request, 'pay_success.html', context={'trade_no': trade_no})
